#include "media_sys.h"


bool vibum(MEDIA_POI mp) //视频总接口
{
    P_VI p_vi = Vlbum_Init(mp);
    if(p_vi == (P_VI)-1)
    {
        printf("视频模块初始化失败！\n");
        return false;
    }


    if(Vlbum_Touch_Ctrl(mp,p_vi) == false)
    {
        printf("视频触摸屏控制失败！\n");
        return false;
    }

    return true;
}


P_VI Vlbum_Init(MEDIA_POI mp) //被sp总接口Album调用
{
    Lcd_Clean(mp,0x00ffffff);

    //申请视频结构体堆空间
    P_VI p_vi = (P_VI)malloc(sizeof(VI));
    if(p_vi == (P_VI)NULL)
    {
        perror("malloc ...");
        return (P_VI)-1;
    }

    memset(p_vi,0,sizeof(VI));


    //创建视频链表头节点
    if((p_vi->mp4_list_head = Create_Mp4_Node()) == (MP4_LINK)-1)//创建视频链表头结点
    {
        printf("创建SP链表头结点失败！\n");
        return (P_VI)-1;
    }

    //视频MP4检索
    if(MP4_File_Search(p_vi) == false)
    {
        printf("MP4视频检索失败！\n");
        return (P_VI)-1;
    }

    //检索进度条
    Show_Ui(mp,"/ui/Bmp_File_Search_Ui.bmp");

    for(int n = 103;n<698;n++)
    {
        for (int y = 303; y < 349; y++)
        {
            int index = y * mp->lcd_w + n;
            *(mp->mmap_start_poi + index) = 0x000000;
        }
        usleep(4000);
    }

    //默认显示第一页缩略图
    if(Show_Page_Thumbnail_Vi(mp,p_vi,1) == false)
    {
        printf("显示sp缩略图失败！\n");
        return (P_VI)-1;
    }

    return p_vi;
}


MP4_LINK  Create_Mp4_Node()  //头结点
{
    MP4_LINK new_node = (MP4_LINK)malloc(sizeof(MP4_NODE));
    if(new_node == (MP4_LINK)NULL)
    {
        perror("malloc bmp node ...");
        return (MP4_LINK)-1;
    }

    memset(new_node,0,sizeof(MP4_NODE));

    new_node->next = new_node;
    new_node->prev = new_node;

    return new_node;
}


bool MP4_File_Search(P_VI p_vi) //MP4视频的检索
{
    //打开存放相册视频的目录
    DIR * dp = opendir(DEFAULT_SEARCH_MP4_PATH);
    if(dp == (DIR *)NULL)
    {
        perror("opendir ...");
        return false;
    }

    //死循环读取文件名字，
    while(1)
    {
        struct dirent * eq = readdir(dp);
        if(eq == (struct dirent * )NULL)
        {
            printf("-----\n");
            break;
        }

        //忽略.和..
        if(eq->d_name[0] == '.') continue;

        //如果是.MP4,倒数第四个字符的下标 = strlen(eq->d_name)-4  -1 p -2 m -3 b -4 .
        
        if((eq->d_type == DT_REG) && (strcmp(&eq->d_name[strlen(eq->d_name)-4],VIDEO_FILE_TYPE) == 0))
        {   
            
            //创建一个节点
            MP4_LINK MP4_node = Create_Mp4_Node();
            if(MP4_node == (MP4_LINK)-1)
            {
                printf("创建视频结点失败！\n");
                return false;
            }

            //保存他的文件路径到节点的MP4_path，
            sprintf(MP4_node->mp4_path,"%s/%s",DEFAULT_SEARCH_MP4_PATH,eq->d_name);

            //头插到链表中
            if(Add_Mp4_Node(p_vi,MP4_node) == false)
            {
                printf("添加视频链表节点失败！\n");
                return false;
            }

            p_vi->video_sum++;//视频数量+1

        }
    }

    //跳出while之后，P_VI->photo_sum就是视频的总数，通过视频的总数去求页数
    if(p_vi->video_sum % 9 == 0)
    {
        p_vi->video_page_sum = p_vi->video_sum / 9;
    }
    else
    {
        p_vi->video_page_sum = p_vi->video_sum / 9 + 1;
    }

    printf("检索视频成功，个数:%d个，页数:%d页，文件如下：\n",p_vi->video_sum,p_vi->video_page_sum);

    //关闭目录
    if(closedir(dp) == -1)
    {
        perror("closedir ...");
        return false;
    }
    return true;
}


bool Add_Mp4_Node(P_VI p_vi,MP4_LINK new_node)  //头插法添加sp链表节点
{
    if(p_vi == (P_VI)NULL || p_vi->mp4_list_head == (MP4_LINK)NULL)
    {
        printf("地址异常！\n");
        return false;
    }

    new_node->prev                  = p_vi->mp4_list_head->prev;
    p_vi->mp4_list_head->prev->next = new_node;

    new_node->next = p_vi->mp4_list_head;

    p_vi->mp4_list_head->prev = new_node;

    return true;
}


bool Show_Page_Thumbnail_Vi(MEDIA_POI mp,P_VI p_vi,int page_num) //指定显示某一页的缩略图   200*120
{
    //如果page  等于1  不用循环
    //如果page 等于 2 也就是第10张开始后面的9张，写一个for循环9次
    //如果page 等于 3 写一个for循环18次


    //获取指定页数在链表的中第一张缩略图的图片节点
    int loop_num = (page_num-1) * 9;

    MP4_LINK obj_mp4_node = p_vi->mp4_list_head->next;

    for(int index=0; index < loop_num; index++)
    {
        obj_mp4_node = obj_mp4_node->next;
    }

    int mp4_x = 10;
    int mp4_y = 20;

    int ascii_x = 10;
    int ascii_y = 140;
    //循环9 次 显示9张缩略图 ，如果当前页数的图片数量不满 9 张 提前 跳出循环
    Show_Ui(mp,"/ui/alb_ui.bmp");
    for(int index = 0; index < 9; index++,obj_mp4_node=obj_mp4_node->next)
    {
        if(obj_mp4_node == p_vi->mp4_list_head) break;

        //显示当前节点对应的视频图标的缩略图
        
        if(Show_One_Thumbnail(mp,"/ui/video_ui.bmp",4,mp4_x,mp4_y) == false)
        {
            printf("显示视频图标缩略图失败！\n");
            return false;
        }

        if(Sentence_Show(&obj_mp4_node->mp4_path[7],mp,ascii_x,ascii_y) == false)
        {
            printf("显示字体失败！\n");
            return false;
        }

        mp4_x += 220;
        ascii_x += 220;

        if(mp4_x > 481)
        {
            mp4_x = 10;
            mp4_y+=150;

            ascii_x = 10;
            ascii_y+=150;
        }
    }
    return true;
}


bool Del_video(int page_num,int n,MEDIA_POI mp,P_VI p_vi)//删除sp
{
    int loop_num = (page_num-1) * 9 + n;

    MP4_LINK obj_mp4_node = p_vi->mp4_list_head->next;

    for(int index=0; index < loop_num; index++)
    {
        obj_mp4_node = obj_mp4_node->next;
    }
    obj_mp4_node->prev->next = obj_mp4_node->next;
    obj_mp4_node->next->prev = obj_mp4_node->prev;

    obj_mp4_node->next = NULL;
    obj_mp4_node->prev = NULL;

    free(obj_mp4_node);
    p_vi->video_sum--;

    if(p_vi->video_sum % 9 == 0)
    {
        p_vi->video_page_sum = p_vi->video_sum / 9;
    }
    else
    {
        p_vi->video_page_sum = p_vi->video_sum / 9 + 1;
    }

    printf("删除成功，个数:%d张，页数:%d页，文件如下：\n",p_vi->video_sum,p_vi->video_page_sum);
    return true;
}


int Video(const char *video_path)  //ship
{
    if (video_path == NULL) 
    {
        system("killall -9 mplayer");  // 强制终止所有MPlayer进程[5](@ref)
        return 0;
    }

    // 终止现有播放进程避免冲突
    system("killall -9 mplayer");

    system("mkfifo /tmp/mplayer_fifo 2>/dev/null");

    // 构建MPlayer命令（适配嵌入式开发板）
    char cmd_buf[256] = {0};
    snprintf(cmd_buf, sizeof(cmd_buf), 
    "mplayer -vo fbdev -framedrop -slave -quiet -input file=/tmp/mplayer_fifo \"%s\" &",
    video_path);

    system(cmd_buf);
    return 0;
}


void *pthread_5(void *arg)
{
    char * mp4_path  = (char *) arg;

    if(Video(mp4_path) == -1)
    {
        printf("sp播放失败！\n");
        return (void *)-1;
    }
    return NULL;
}


bool show_video(int page_num,int n,MEDIA_POI mp,P_VI p_vi)//显示视频 n是视频位置
{
    pthread_t id_5;

    P_VIDEO_I Vi = (P_VIDEO_I)malloc(sizeof(VIDEO_I));
    if(Vi == (P_VIDEO_I)NULL)
    {
        perror("malloc ...");
        return (Vi)-1;
    }

    int loop_num = (page_num-1) * 9 + n;

    MP4_LINK obj_mp4_node = p_vi->mp4_list_head->next;

    for(int index=0; index < loop_num; index++)
    {
        obj_mp4_node = obj_mp4_node->next;
    }
    int a=1;
    while(1)
    {
        if(a==1 && loop_num < p_vi->video_sum)
        {
            a=0;
            if(pthread_create(&id_5,NULL,pthread_5,obj_mp4_node->mp4_path) != 0)
            {
                perror("pthread_cread_create ...");
                return -1;
            } 
            pthread_join(id_5, NULL);
        }

        if(Get_Touch_Xy(mp,0) == false)
        {
            printf("读取触摸屏坐标失败！\n");
            return false;
        }

        if(mp->touch_x > 600 && mp->touch_x < 800 && mp->touch_y > 0 && mp->touch_y < 150)//tui
        {
            system("killall -9 mplayer");
            break;
        }

        if(mp->touch_x > 350 && mp->touch_x < 550 && mp->touch_y > 190 && mp->touch_y < 290)//tin
        {
            FILE *fifo = fopen("/tmp/mplayer_fifo", "w");
            if (fifo) 
            {
                fprintf(fifo, "pause\n");
                fclose(fifo);
            }
        }

        if(mp->touch_x > 0 && mp->touch_x < 300 && mp->touch_y > 300 && mp->touch_y < 480)//shang
        {
            obj_mp4_node = obj_mp4_node->prev;
            if (obj_mp4_node == p_vi->mp4_list_head)
            {
                obj_mp4_node = obj_mp4_node->next;
                continue;
            }
            else
            system("killall -9 mplayer");
            a=1;
        }

        if(mp->touch_x > 500 && mp->touch_x < 800 && mp->touch_y > 300 && mp->touch_y < 480)//xia
        {
            obj_mp4_node = obj_mp4_node->next;
            if (obj_mp4_node == p_vi->mp4_list_head)
            {
                obj_mp4_node = obj_mp4_node->prev;
                continue;
            }
            else
            system("killall -9 mplayer");
            a=1;
        }
    }
    
    return true;
}


bool Vlbum_Touch_Ctrl(MEDIA_POI mp,P_VI p_vi)//sp界面触摸控制
{
    int page_num = 1;
    while(1)
    {
        //先获取点击的触摸坐标，再去判断坐标是哪个按钮的区间
        if(Get_Touch_Xy(mp,0) == false)
        {
            printf("读取触摸屏坐标失败！\n");
            return false;
        }

        if(mp->touch_x > 700 && mp->touch_x < 800 && mp->touch_y > 240 && mp->touch_y < 360 && page_num > 1) //上一页
        {
            printf("上一页 !\n");
            if(Show_Page_Thumbnail_Vi(mp,p_vi,--page_num) == false)
            {
                printf("显示缩略图失败！\n");
                return (P_VI)-1;
            }
        
        }
        else if(mp->touch_x > 700 && mp->touch_x < 800 && mp->touch_y > 360 && mp->touch_y < 480 && page_num < p_vi->video_page_sum) //下一页
        {
            printf("下一页 !\n");
            if(Show_Page_Thumbnail_Vi(mp,p_vi,++page_num) == false)
            {
                printf("显示缩略图失败！\n");
                return (P_VI)-1;
            }
        }
        else if(mp->touch_x > 700 && mp->touch_x < 800 && mp->touch_y > 0 && mp->touch_y < 120) //退出返回主界面
        {
            //显示主界面
            time_up_down = 1;
            if(Show_Ui(mp,"/ui/main_ui.bmp") == false)
            {
                printf("显示主界面失败！\n");
                return false;
            }
            mp->touch_x = -1;
            mp->touch_y = -1;

            if (close_video_link(p_vi) == false)
            {
                printf("摧毁失败！\n");
                return false;
            }
            free(p_vi);
            break;
        }else if(mp->touch_x > 700 && mp->touch_x < 800 && mp->touch_y > 120 && mp->touch_y < 240)//删除图片
        {
            
            int col = -1, row = -1;

            while (1)
            {
                if(Get_Touch_Xy(mp,0) == false)
                {
                    printf("读取触摸屏坐标失败！\n");
                    return false;
                }
                
                // 列坐标判断（横向间隔20像素，每列宽200）
                if (mp->touch_x > 10 && mp->touch_x < 210) col = 0;
                else if (mp->touch_x > 230 && mp->touch_x < 430) col = 1;
                else if (mp->touch_x > 450 && mp->touch_x < 650) col = 2;

                // 行坐标判断（纵向间隔20像素，每行高120）
                if (mp->touch_y > 10 && mp->touch_y < 130) row = 0;
                else if (mp->touch_y > 150 && mp->touch_y < 270) row = 1;
                else if (mp->touch_y > 290 && mp->touch_y < 410) row = 2;

                if (col != -1 && row != -1) 
                {
                    if(Del_video(page_num,row * 3 + col,mp,p_vi) == true) break;
                }
            }

            if(Show_Page_Thumbnail_Vi(mp,p_vi,page_num) == false)
            {
                printf("显示缩略图失败！\n");
                return false;
            }
            
        }
        else
        {
            int col = -1, row = -1;

            // 列坐标判断（横向间隔20像素，每列宽200）
            if (mp->touch_x > 10 && mp->touch_x < 210) col = 0;
            else if (mp->touch_x > 230 && mp->touch_x < 430) col = 1;
            else if (mp->touch_x > 450 && mp->touch_x < 650) col = 2;

            // 行坐标判断（纵向间隔20像素，每行高120）
            if (mp->touch_y > 10 && mp->touch_y < 130) row = 0;
            else if (mp->touch_y > 150 && mp->touch_y < 270) row = 1;
            else if (mp->touch_y > 290 && mp->touch_y < 410) row = 2;

            if (col != -1 && row != -1) 
            {
                if(show_video(page_num, row * 3 + col, mp, p_vi) == false)
                {
                    printf("显示sp失败！\n");
                    return false;
                }
                if(Show_Page_Thumbnail_Vi(mp,p_vi,page_num) == false)
                {
                    printf("显示缩略图失败！\n");
                    return false;
                }
            }
        }
    }


    return true;
}


bool close_video_link(P_VI pv_i)//cuihui
{
    
    if (pv_i->mp4_list_head == (MP4_LINK)NULL)
    {
        printf("头结点异常\n");
        return false;
    }

    while(pv_i->mp4_list_head->next != pv_i->mp4_list_head)
    {
        MP4_LINK del_node = pv_i->mp4_list_head->next;

        del_node->prev->next = del_node->next;
        del_node->next->prev = del_node->prev;

        del_node->prev = NULL;
        del_node->next = NULL;

        free(del_node);
    }
    free(pv_i->mp4_list_head);

    printf("cgcgcgcgc\n");

    return true;
}